<template>
  <div class="slider" ref="slider">
		<div class="slider-group" ref="sliderGroup">
			<slot></slot>
		</div>
  </div>
</template>

<script>
import BScroll from 'better-scroll'

export default {
name: 'slider',
	props: {
		loop: {
			type: Boolean,
			default: false
		},
		interval: {
			type: Number,
			default: 4000
		}
	},
	data() {
		return {
			currentPageIndex: 0
		}
	},
	mounted() {
		setTimeout(() => {
			this._setSliderWidth()
			this._initSlider()
		}, 20)

		window.addEventListener('resize', () => {
			if (!this.slider) {
				return
			}
			this._setSliderWidth(true)
			this.slider.refresh()
		})
	},
	destroyed() {
		clearTimeout(this.timer)
	},
	methods: {
		_setSliderWidth(isResize) {
			this.children = this.$refs.sliderGroup.children

			let width = 0
			let sliderWidth = this.$refs.slider.clientWidth
			for (let i = 0; i < this.children.length; i++) {
				let child = this.children[i]
				child.classList.add('slider-item')

				child.style.width = sliderWidth + 'px'
				width += sliderWidth
			}
			if (this.loop && !isResize) {
				width += 2 * sliderWidth
			}
			this.$refs.sliderGroup.style.width = width + 'px'
		},
		_initSlider() {
			this.slider = new BScroll(this.$refs.slider, {
				scrollX: true,
				scrollY: false,
				momentum: false,
				snap: {
					loop: this.loop,
					threshold: 130
				},
				useTransition: true,
				bounce: false,
				probeType: 2
			})

			this.slider.on('scrollEnd', () => {
				let pageIndex = this.slider.getCurrentPage().pageX
				if (this.loop) {
					pageIndex -= 1
				}

				if (this.currentPageIndex !== pageIndex) {
					this.currentPageIndex = pageIndex
					this.$emit('change', pageIndex)
				}
			})
		},
		_play() {
			let pageIndex = this.currentPageIndex + 1
			if (this.loop) {
				pageIndex += 1
			}
			this.timer = setTimeout(() => {
				this.slider.goToPage(pageIndex, 0, 400)
			}, this.interval)
		},
		goToPage() {
			// this.slider && this.slider.goToPage(pageIndex, 0, 400)
			this.slider && this.slider.goToPage.apply(this.slider, arguments)
		}
	}
}
</script>

<style scoped lang="less">
  
.slider{
	min-height: 1px;
	height: 100%;
	.slider-group{
		position: relative;
		overflow: hidden;
		white-space: nowrap;
		.slider-item{
			float: left;
			box-sizing: border-box;
			overflow: hidden;
		}
	}
}
</style>